﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class PVEChapterSelectMenu : MonoBehaviour {

    static PVEChapterSelectMenu instance;
    // 이벤트 열지 말지 유무
    static int[] s_EventMapID;  // 열어줄 이벤트 아이디값 저장
    // PVE메뉴 프리펩
    static GameObject s_Prefab;
    // PVE메뉴 프리펩 리소스 위치
    const string PrefabPath = "Prefabs/PVEChapterSelectMenu/PVEChapterSelectMenu";
    // 부모 노드
    const string ParentPath = "UI Root (2D)/Camera/Anchor";
    // XML ID 배열
    static List<int> s_PVEIDs;
    // 선택된 맵 인덱스 저장
    static int s_SelectMapIndex;
    // 한화면에 보일수있는 맵 최대 갯수
    const int NumofMaxMap = 5;  //해당 수보다 맵챕터가 많아지면 스크롤뷰 사용

    GameObject m_SelectBox;
    GameObject[] m_SingleMap; 

    static public void OpenMenu()
    {
        if (instance == null)
        {
            if (s_EventMapID == null)       // 테스트 코드
            {
                s_EventMapID = new int[] { };
            }

            if (s_PVEIDs == null)
            {
                s_PVEIDs = new List<int>();

                int[] tempArray = CPVEStageDataManager.Instance.GetPVEStageIDs();

                int EventIDNum = 0;
                for(int i = 0; i < tempArray.Length ; i++)
                {
                    if (tempArray[i] <= 1000)
                        s_PVEIDs.Add(tempArray[i]);
                    else
                    {
                        for (int j = 0; j < s_EventMapID.Length; j++)
                        {
                            if(s_EventMapID[j] == tempArray[i])
                                s_PVEIDs.Add(tempArray[i]);
                        }
                    }                   
                }

                int ArrayLength = tempArray.Length - EventIDNum + s_EventMapID.Length;
            }

            if(s_Prefab == null)
                s_Prefab = Resources.Load(PrefabPath) as GameObject;

            GameObject tempObj = Instantiate(s_Prefab) as GameObject;

            tempObj.name = "PVEChapterSelectMenu";          

            GameObject UiRoot = GameObject.Find(ParentPath);

            tempObj.transform.parent = UiRoot.transform;
            tempObj.transform.localScale = Vector3.one;
            tempObj.transform.localPosition = Vector3.zero;


            instance = tempObj.GetComponent("PVEChapterSelectMenu") as PVEChapterSelectMenu;

        }

        instance.SetMenuWithData();
		LTDefine.SetAllChildTransformLayer(instance.transform, LayerMask.NameToLayer("GUI_TOP"));
        instance.gameObject.SetActive(true);
    }

    void SetMenuWithData()
    {
        if (m_SingleMap == null)
        {
            m_SingleMap = new GameObject[s_PVEIDs.Count];
        }

        UIScrollView ScrollPanel = transform.FindChild("Panel").GetComponent("UIScrollView") as UIScrollView;
        Transform gridTransform = ScrollPanel.transform.FindChild("Grid");

        float startPosx = -445;

        if (m_SingleMap.Length <= NumofMaxMap)        
        {
            ScrollPanel.enabled = false;
            ScrollPanel.transform.localPosition = Vector3.zero;
            startPosx = -1.0f * ((m_SingleMap.Length - 1) * 240.0f) / 2.0f;
        }

        for (int i = 0; i < m_SingleMap.Length; i++)
        {
            if (m_SingleMap[i] == null)
            {
                if (i == 0)
                    m_SingleMap[i] = GameObject.Find("Grid/SingleMap");
                else                
                    m_SingleMap[i] = Instantiate(m_SingleMap[0]) as GameObject;

                UIDragScrollView tempDSV = m_SingleMap[i].GetComponent("UIDragScrollView") as UIDragScrollView;
                if (m_SingleMap.Length > NumofMaxMap)
                    tempDSV.scrollView = ScrollPanel;
                else
                    tempDSV.scrollView = null;

                UIButtonMessage tempBM = m_SingleMap[i].GetComponent("UIButtonMessage") as UIButtonMessage;
                tempBM.target = gameObject;
                tempBM.functionName = "OnSingleMap";

                UISprite tempSt = m_SingleMap[i].GetComponent("UISprite") as UISprite;      // 임시 이미지 변경
                tempSt.spriteName = string.Format("Ui_StageBtn{0:00}", (i % 5) + 1);
            }

            m_SingleMap[i].transform.parent = gridTransform;
            m_SingleMap[i].transform.localScale = Vector3.one;           

            m_SingleMap[i].transform.localPosition = new Vector3(startPosx + (i * 240), 0, 0);

            CPVEStageData data = CPVEStageDataManager.Instance.GetPVEStageData(s_PVEIDs[i]);
            UILabel nameLabel = m_SingleMap[i].transform.FindChild("mapName").GetComponent("UILabel") as UILabel;
            UILabel stageLabel = m_SingleMap[i].transform.FindChild("stageLabel").GetComponent("UILabel") as UILabel;

            GameObject hidePlane = m_SingleMap[i].transform.FindChild("HidePlane").gameObject;
                     

            if (i + 1 < MyInfo.Instance.MyPVEStageInfo.StoryMode)  // stage 깨야할 스테이지 들어감
            {
                if (data.stage_type == StageType.story)
                    stageLabel.text = string.Format("{0} stage \nClear", i + 1);
                else
                    stageLabel.text = "";
           
                nameLabel.text = data.map_name;// +"\n Clear";
                hidePlane.SetActive(false);
            }
            else if (i + 1 == MyInfo.Instance.MyPVEStageInfo.StoryMode)
            {
                if (data.stage_type == StageType.story)
                    stageLabel.text = string.Format("{0} stage\n Current", i + 1);
                else
                    stageLabel.text = "";

                nameLabel.text = data.map_name;//; +"\n Current";
                hidePlane.SetActive(false);
            }
            else
            {
                if (data.stage_type == StageType.story)
                    stageLabel.text = string.Format("{0} stage", i + 1);
                else
                    stageLabel.text = "";

                nameLabel.text = data.map_name;// +"\n Not yet";
                hidePlane.SetActive(true);

                UIButtonMessage tempBM = m_SingleMap[i].GetComponent("UIButtonMessage") as UIButtonMessage;
                tempBM.target = null;
                tempBM.functionName = "";
            }            

            UILabel stageBodyLabel = m_SingleMap[i].transform.FindChild("mapStageBody").GetComponent("UILabel") as UILabel;
            stageBodyLabel.text = data.stage_desc_body;
        }

        m_SelectBox = m_SingleMap[0].transform.parent.FindChild("MapSelectBox").gameObject;
        m_SelectBox.SetActive(false);
    }

    void OnSingleMap(GameObject button)
    {
        for (int i = 0; i < m_SingleMap.Length; i++)
        {
            if (m_SingleMap[i] == button)
            {
                s_SelectMapIndex = i;

                m_SelectBox.SetActive(true);

                Vector3 pos = m_SelectBox.transform.localPosition;
                pos.x = button.transform.localPosition.x;
                m_SelectBox.transform.localPosition = pos;

                ///////////////////
                CPVEStageData tmpData = CPVEStageDataManager.Instance.GetPVEStageData(s_SelectMapIndex + 1);
                CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;

                if (c != null)
                {
                    c.RequestJoinToMaster(JoinType.JT_SINGLE_JOIN, "", "map_" + tmpData.map_name, "", tmpData.id);
                }
                ///////////////////
                
                LoadingWindow.window.ShowShortLoading();
                StartCoroutine("TimeOutOfJoinGame");
                break;
            }
            
            //Camera.mainCamera.renderer.sortingOrder
        }
    }

    IEnumerator TimeOutOfJoinGame()
    {
        yield return new WaitForSeconds(5.0f);
        LoadingWindow.window.HideLoading();
    }

    void CloseMenu(GameObject param)
    {
        gameObject.SetActive(false);
    }
}
